{"cells":[{"cell_type":"markdown","metadata":{"id":"11n5gndbRzoY"},"source":["# Programming and Basic Structure in Python\n"]},{"cell_type":"markdown","metadata":{"id":"AIFsv_RZ1iV0"},"source":["\n"," \n"," \n","
\n"," \"Open\n"," \n"," \n","
"]},{"cell_type":"markdown","metadata":{"id":"wJjIP5Vne7cM"},"source":["In the earliest days of computers, the only programming languages available were machine languages. Each computer had its own machine language, which was made of streams of 0s and 1s. In Chapter 5 we showed that in a primitive hypothetical computer, we need to use 11 lines of code to read two integers, add them, and print the result.\n","\n","\n","> The only language understood by a computer is machine language.\n","\n","It has at least two drawbacks\n","1. It is machine-dependent. The machine language of one computer is different than the machine language of another computer if they use different hardware. \n","2. Second, it is very tedious to write programs in this language and very difficult to find errors.\n","\n","The machine language to add two integers are:\n","\n","
\n"]},{"cell_type":"markdown","metadata":{"id":"Ov2zGQZ0fpWN"},"source":["The next evolution in programming came with the idea of replacing binary code for instruction and addresses with symbols or mnemonics. Because they used symbols, these languages were first known as **symbolic languages**. The set of these mnemonic languages were later referred to as **assembly languages**. A special program called an **assembler** is used to translate code in assembly language into machine language. The assembly language for our hypothetical computer to add two intergers are:"]},{"cell_type":"markdown","metadata":{"id":"ysPAJS9jnuXm"},"source":["
\n","\n"]},{"cell_type":"markdown","metadata":{"id":"LdvzSD5df2aj"},"source":["Although assembly languages greatly improved programming efficiency, they still required programmers to concentrate on the hardware they were using. Working with symbolic languages was also very tedious, because each machine instruction had to be individually coded. The desire to improve programmer efficiency and to change the focus from the computer to the problem being solved led to the development of **high-level languages**. High-level languages are portable to many different computers, allowing the programmer to concentrate on the application rather than the intricacies of the computer’s organization.\n","\n","High-level languages share one characteristic with symbolic languages: they must be converted to machine language. The program in a high-level language is called the *source program*. The translated program in machine language is called the *object program*. This process is called **interpretation** or **compilation** which needs an `interpreter` and a compiler.\n","\n"]},{"cell_type":"markdown","metadata":{"id":"NUbpJomFdNWq"},"source":["Compilation will first preprocess or translate the whole source program into the object module before executing the program. Interpretation, on the other hand, will process and translating each line of the source program into the corresponding line of the object program and executing the translated line."]},{"cell_type":"markdown","metadata":{"id":"q6YVeAxAn3hM"},"source":["
"]},{"cell_type":"markdown","metadata":{"id":"pvz16w-wnJox"},"source":["The high-level language to add two integers are:"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"6NSZgDSlhvYB"},"outputs":[],"source":["a = input(\"Please input a: \")\n","b = input(\"Please input b: \")\n","c = int(a) + int(b)\n","print(\"The sum is: \"+str(c))"]},{"cell_type":"markdown","metadata":{"id":"artxU0h8hEip"},"source":["Python is a type of interpreted language while C/C++ are compiled language."]},{"cell_type":"markdown","metadata":{"id":"KiMWFy98vciM"},"source":["#### > Exercise 0: Try to calculate 1+2...+100 using loops and print the intermediate results every 10 iterations. Remember that indentation is significant in Python!"]},{"cell_type":"code","execution_count":null,"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"elapsed":2,"status":"ok","timestamp":1668595952301,"user":{"displayName":"phonchi chung","userId":"13517391734500420886"},"user_tz":-480},"id":"TYMzVP5yvrQj","outputId":"3db6c919-25fc-4f94-9819-3521ecd37096"},"outputs":[{"name":"stdout","output_type":"stream","text":["55\n","210\n","465\n","820\n","1275\n","1830\n","2485\n","3240\n","4095\n","5050\n"]}],"source":["sum = 0 # intermediate reults\n","i = 1 # counter\n","while ():\n"," # Actual calculation\n"," if ():\n"," print() # Print the intermediate results\n"," i = i + 1 # Increment the counter"]},{"cell_type":"code","execution_count":null,"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"elapsed":310,"status":"ok","timestamp":1668595955706,"user":{"displayName":"phonchi chung","userId":"13517391734500420886"},"user_tz":-480},"id":"mlMWEVZ3wLbi","outputId":"9a3c3523-1846-40a5-9bf2-82f1ce674669"},"outputs":[{"name":"stdout","output_type":"stream","text":["5050\n"]}],"source":["print(sum)"]},{"cell_type":"markdown","metadata":{"id":"-emVEnBdg56N"},"source":["To review the basic concepts of programming language please refer to the previous two labs. Now we are going to introduce the basic structure in python that will help you to program in the following chapters."]},{"cell_type":"markdown","metadata":{"id":"SwFKFBMwRzoa"},"source":["## String"]},{"cell_type":"markdown","metadata":{"id":"xtOzCNTJcj3N"},"source":["There are several ways to create a new string; the simplest is to enclose the elements in quotes:"]},{"cell_type":"code","execution_count":null,"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"elapsed":4,"status":"ok","timestamp":1668686223113,"user":{"displayName":"phonchi chung","userId":"13517391734500420886"},"user_tz":-480},"id":"ossL66xxcoGg","outputId":"6fac1a14-1607-409b-c6f1-0b05188f6e2c"},"outputs":[{"data":{"text/plain":["str"]},"execution_count":2,"metadata":{},"output_type":"execute_result"}],"source":["type('')"]},{"cell_type":"markdown","metadata":{"id":"Ss9hRGHDRzob"},"source":["A string is a **sequence of case sensitive characters**. You can access the characters one at a time with the bracket operator:"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"4X-QB57Sqxbu"},"outputs":[],"source":["fruit = 'banana'\n","letter = fruit[1]\n","print(letter)"]},{"cell_type":"markdown","metadata":{"id":"TVuZi_rfsC9u"},"source":["The expression in brackets is called an index. The index indicates which character in the sequence you want.\n","\n","Note that in Python, the index is starting from zero!"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"QYptoP__sAbn"},"outputs":[],"source":["letter = fruit[0]\n","print(letter)"]},{"cell_type":"markdown","metadata":{"id":"cc7LkxgesPQf"},"source":["So “b” is the 0th letter (“zero-th”) of “banana”, “a” is the 1th letter (“one-th”), and “n” is the 2th (“two-th”) letter.\n","\n","
\n","
source: https://www.py4e.com/html3/06-strings
"]},{"cell_type":"markdown","metadata":{"id":"GQ-v5PkhrxLt"},"source":["`len` is a built-in function that returns the number of characters in a string:"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"9eio5IH1sRe_"},"outputs":[],"source":["len(fruit)"]},{"cell_type":"markdown","metadata":{"id":"DoBusgVgs4sP"},"source":["To get the last letter of a string, you can use something like this:"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"L2QkmB_JsBSu"},"outputs":[],"source":["length = len(fruit)\n","fruit[length-1]"]},{"cell_type":"markdown","metadata":{"id":"BCdYJtfCsNTk"},"source":["Since we started counting at zero, to get the last character, you have to subtract 1 from length. Alternatively, you can use negative indices, which count backward from the end of the string."]},{"cell_type":"code","execution_count":null,"metadata":{"id":"2kdWhLASsWjM"},"outputs":[],"source":["fruit[-1], fruit[-2]"]},{"cell_type":"markdown","metadata":{"id":"6Wuos2Qs98jG"},"source":["In Python 3, all strings are Unicode!"]},{"cell_type":"markdown","metadata":{"id":"n3ezAAdIsgpj"},"source":["### String slices"]},{"cell_type":"markdown","metadata":{"id":"MZguDlIUuGmy"},"source":["A segment of a string is called a *slice*. Selecting a slice is similar to selecting a character:"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"izhaD7_3uJ9t"},"outputs":[],"source":["s = 'Cool Python'\n","print(s[0:4])"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"iG-YD_FUuTTv"},"outputs":[],"source":["print(s[5:11])"]},{"cell_type":"markdown","metadata":{"id":"UxmXixesudSF"},"source":["You can slice strings using `[start:stop:step]`. The operator `[start:stop]` returns the part of the string from the “start-th” character to the “stop-th” character, including the first but excluding the last with `step=1`.\n","\n","If you omit the first index (before the colon), the slice starts at the beginning of the string. If you omit the second index, the slice goes to the end of the string:"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"2fPn1ShJubZo"},"outputs":[],"source":["s[:5] #same as s[0:5] "]},{"cell_type":"code","execution_count":null,"metadata":{"id":"iYBocApPvmiB"},"outputs":[],"source":["s[5:] #same as s[5:len(s)] "]},{"cell_type":"code","execution_count":null,"metadata":{"id":"5tRijpT_ushh"},"outputs":[],"source":["s[::2] #same as s[0:len(s):2]"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"kpVQnmvvwScw"},"outputs":[],"source":["s[::] #same as s[0:len(s):1]"]},{"cell_type":"markdown","metadata":{"id":"WAHCar15v8gq"},"source":["To reverse a string, there is a special syntax as follows:"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"fXso2-zsu33S"},"outputs":[],"source":["s[::-1] #same as s[-1:-(len(s)+1):-1]"]},{"cell_type":"markdown","metadata":{"id":"7RePo7y6wYjw"},"source":["Strings are “immutable” which mean that it cannot be modified "]},{"cell_type":"code","execution_count":null,"metadata":{"id":"uYrfWa9lwFFx"},"outputs":[],"source":["s = \"hello\"\n","s[0] = 'y' "]},{"cell_type":"markdown","metadata":{"id":"775wqKWHwtGa"},"source":["The “object” in this case is the string and the “item” is the character you tried to assign. The best you can do is create a new string that is a variation on the original:"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"YuVQIH1XwfID"},"outputs":[],"source":["s = 'y'+s[1:len(s)]\n","s"]},{"cell_type":"markdown","metadata":{"id":"gASYx5-Cxzyg"},"source":["### String traversal"]},{"cell_type":"markdown","metadata":{"id":"zq-Y5gN7x64f"},"source":["A lot of computations involve processing a string one character at a time. Often they start at the beginning, select each character in turn, do something to it, and continue until the end. This pattern of processing is called a traversal"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"xcHprgHtw91Y"},"outputs":[],"source":["index = 0\n","while index < len(s):\n"," if s[index] == 'o':\n"," print(\"There is an o\")\n"," index = index + 1"]},{"cell_type":"markdown","metadata":{"id":"p1B6qCHTyjpP"},"source":["The loop condition is `index < len(s)`, so when index is equal to the length of the string, the condition is `false`, and the body of the loop is not executed. The last character accessed is the one with the index `len(s)-1`, which is the last character in the string."]},{"cell_type":"markdown","metadata":{"id":"wRBH-OIEzOZL"},"source":["The `range` returns a list of indices from `0` to `n − 1`, where `n` is the length of the list.\n","\n","> More generally, `range(lower, upper, step)` returns an iterable of numbers from the lower number to the upper number, while incrementing by step. "]},{"cell_type":"markdown","metadata":{"id":"dZMbIcFTyt-Q"},"source":["Another way to write a traversal is with a `for` loop:"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"22fq9pCezegR"},"outputs":[],"source":["for index in range(len(s)):\n"," if s[index] == 'o':\n"," print(\"There is an o\")"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"eFWUxp6syZjf"},"outputs":[],"source":["for char in s:\n"," if char == 'o':\n"," print(\"There is an o\")"]},{"cell_type":"markdown","metadata":{"id":"2kLRVhae3rSa"},"source":["### > Exercise 1: Try to write a function that counts the number of times the letter “a” appears in a string"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"KeFcWZEpy0cJ"},"outputs":[],"source":["def count(word, letter):\n"," \"\"\"\n"," Parameters\n"," ----------\n"," word: str\n"," The input string\n"," letter: str\n"," The letter that we want to count the ocurrence\n"," Returns\n"," -------\n"," count : int\n"," The number of times the letter appears in the word\n"," \"\"\"\n"," # Your code here\n"," return count"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"HJXZxjUr4SRS"},"outputs":[],"source":["assert(count('nsysu','s')==2)\n","assert(count('math','s')==0)"]},{"cell_type":"markdown","metadata":{"id":"DPpfFEA07W0A"},"source":["### String method"]},{"cell_type":"markdown","metadata":{"id":"zFPpUx5w7al_"},"source":["Strings are an example of Python objects. An object contains both data (the actual string itself) and methods, which are effectively functions that are built into the object and are available to any instance of the object."]},{"cell_type":"markdown","metadata":{"id":"894SyVBC7fbO"},"source":["Python has a function called `dir` which lists the methods available for an object. "]},{"cell_type":"code","execution_count":null,"metadata":{"id":"hfQPXKNF7ZzM"},"outputs":[],"source":["dir(s)"]},{"cell_type":"markdown","metadata":{"id":"BtXyvNIT7ncg"},"source":["While the `dir` function lists the methods, and you can use `help` to get some simple documentation on a method, a better source of documentation for string methods would be https://docs.python.org/library/stdtypes.html#string-methods."]},{"cell_type":"markdown","metadata":{"id":"c3-QOR977r1n"},"source":["Calling a method is similar to calling a function (it takes arguments and returns a value) but the syntax is different. We call a method by appending the method name to the variable name using the period as a delimiter."]},{"cell_type":"markdown","metadata":{"id":"IW0YW38g74I3"},"source":["For example, the method `count` takes a latter and returns the number of times the letter appears in a string: Instead of the function syntax `count(word, letter)`, it uses the method syntax `word.count(letter)`."]},{"cell_type":"code","execution_count":null,"metadata":{"id":"cj8XwFy47hwe"},"outputs":[],"source":["'nsysu'.count('s')"]},{"cell_type":"markdown","metadata":{"id":"ZQ9XzbIq8v0q"},"source":["One common task is to remove white space (spaces, tabs, or newlines) from the beginning and end of a string using the `strip` method:"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"LK2pje2y72CZ"},"outputs":[],"source":["line = ' Here we go '\n","line.strip()"]},{"cell_type":"markdown","metadata":{"id":"M-PIrdKX-Kz_"},"source":["The `replace()` function is like a “search and replace” operation in a word processor\n"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"GOiICZMo-Mn-"},"outputs":[],"source":["greet = 'Hello Bob'\n","nstr = greet.replace('Bob','Jane')\n","print(nstr)"]},{"cell_type":"markdown","metadata":{"id":"uloOTsPL9A74"},"source":["### Format operator"]},{"cell_type":"markdown","metadata":{"id":"4fqA_4TV9DiW"},"source":["The format operator, `%` allows us to construct strings, replacing parts of the strings with the data stored in variables. When applied to integers, `%` is the modulus operator. But when the first operand is a string, `%` is the format operator."]},{"cell_type":"markdown","metadata":{"id":"HoP5PNW-9Jk_"},"source":["The first operand is the format string, which contains one or more format sequences that specify how the second operand is formatted. The result is a string."]},{"cell_type":"markdown","metadata":{"id":"gD9lCR-l9PFO"},"source":["For example, the format sequence `%d` means that the second operand should be formatted as an integer (“d” stands for “decimal”):"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"XUVfczP09OJR"},"outputs":[],"source":["camels = 42\n","'%d' % camels"]},{"cell_type":"markdown","metadata":{"id":"JQilFDZB9dPP"},"source":["If there is more than one format sequence in the string, the second argument has to be a tuple. Each format sequence is matched with an element of the tuple, in order."]},{"cell_type":"markdown","metadata":{"id":"2nmfASHN9iiF"},"source":["The following example uses `%d` to format an integer, `%g` to format a floating-point number, and %s to format a string:"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"qgfevIe19eHx"},"outputs":[],"source":["'In %d years I have spotted %g %s.' % (3, 0.1, 'camels')"]},{"cell_type":"markdown","metadata":{"id":"MTJO4K049nuU"},"source":["## List"]},{"cell_type":"markdown","metadata":{"id":"iyiuJDms-ZlA"},"source":["Like a string, a list is a sequence of values. In a string, the values are characters; in a list, they can be any type. The values in list are called elements or sometimes items.\n","\n","
\n","
source: https://favtutor.com/blogs/list-vs-dictionary
\n","\n","There are several ways to create a new list; the simplest is to enclose the elements in square brackets (“[” and ”]”):"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"_UZvUFCrqFdC"},"outputs":[],"source":["type([])"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"iA6_fB0H9onD"},"outputs":[],"source":["[10, 20, 30, 40], ['calculus', 'introduction to mathematics', 'introduction to computer science', 'linear algebra']"]},{"cell_type":"markdown","metadata":{"id":"jPqRNKXB-03e"},"source":["The first example is a list of four integers. The second is a list of four strings. The elements of a list don’t have to be the same type. The following list contains a string, a float, an integer, and (lo!) another list:"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"CQZ2OKWt-pRz"},"outputs":[],"source":["['spam', 2.0, 5, [10, 20]]"]},{"cell_type":"markdown","metadata":{"id":"EC0ZbOnD-7p8"},"source":["A list that contains no elements is called an empty list; you can create one with empty brackets."]},{"cell_type":"code","execution_count":null,"metadata":{"id":"geeASg-N-4O3"},"outputs":[],"source":["[]"]},{"cell_type":"markdown","metadata":{"id":"srlcPSxA_DhN"},"source":["The syntax for accessing the elements of a list is the same as for accessing the characters of a string: the bracket operator. The expression inside the brackets specifies the index. Remember that the indices start at 0:"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"wrpckWiU-9W8"},"outputs":[],"source":["subjects = ['calculus', 'introduction to mathematics', 'introduction to computer science', 'linear algebra']\n","print(subjects[0])"]},{"cell_type":"markdown","metadata":{"id":"Ylv8bDoR_uZe"},"source":["Unlike strings, lists are mutable because you can change the order of items in a list or reassign an item in a list. When the bracket operator appears on the left side of an assignment, it identifies the element of the list that will be assigned."]},{"cell_type":"code","execution_count":null,"metadata":{"id":"xtumYSz9_M-s"},"outputs":[],"source":["numbers = [17, 123, 42, 7]\n","numbers[1] = 5\n","numbers"]},{"cell_type":"markdown","metadata":{"id":"0K-ICEPo_4rQ"},"source":["The one-th element of numbers, which used to be 123, is now 5.\n","\n","You can think of a list as a relationship between indices and elements. This relationship is called a mapping; each index “maps to” one of the elements.\n","\n","List indices work the same way as string indices:\n","\n","* Any integer expression can be used as an index.\n","\n","* If you try to read or write an element that does not exist, you get an IndexError.\n","\n","* If an index has a negative value, it counts backward from the end of the list."]},{"cell_type":"markdown","metadata":{"id":"3hD9uBt6AW9l"},"source":["### List slices"]},{"cell_type":"markdown","metadata":{"id":"E8mL5olDAY4U"},"source":["The slice operator also works on lists:"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"GSXTttiHARSr"},"outputs":[],"source":["t = ['a', 'b', 'c', 'd', 'e', 'f']\n","t[1:3], t[2:-1], t[4:]"]},{"cell_type":"markdown","metadata":{"id":"IvviPig3At12"},"source":["### List traversal"]},{"cell_type":"markdown","metadata":{"id":"JwenWwmtAy78"},"source":["The most common way to traverse the elements of a list is with a for loop. The syntax is the same as for strings:"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"9X-CrgFjAjZM"},"outputs":[],"source":["for subject in subjects:\n"," print(subject)"]},{"cell_type":"markdown","metadata":{"id":"OYn3-mOZA_WV"},"source":["This works well if you only need to read the elements of the list. But if you want to write or update the elements, you need the indices. A common way to do that is to combine the functions `range` and `len`:"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"JCzxSstzA8Qm"},"outputs":[],"source":["sum = 0\n","for i in range(len(numbers)):\n"," print(i, sum)\n"," sum = numbers[i] + sum"]},{"cell_type":"markdown","metadata":{"id":"720JXEBDBQhl"},"source":["This loop traverses the list and prints each element. `len` returns the number of elements in the list. `range` returns a list of indices from `0` to `n − 1`, where `n` is the length of the list. Each time through the loop, `i` gets the index of the next element."]},{"cell_type":"markdown","metadata":{"id":"9aL7ZSywRpjY"},"source":["Instead of using the `range(len(someList))` technique with a for loop to obtain the integer index of the items in the list, you can call the `enumerate()` function instead. On each iteration of the loop, `enumerate()` will return two values: the index of the item in the list, and the item in the list itself."]},{"cell_type":"code","execution_count":null,"metadata":{"id":"PILF96yHRu83"},"outputs":[],"source":["sum = 0\n","for i, item in enumerate(numbers):\n"," print(i, sum)\n"," sum = item + sum"]},{"cell_type":"markdown","metadata":{"id":"HQK5zGP749m3"},"source":["### > Exercise 2: Try to write a function that calculates the average of the input list"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"XcW7cP0qUER9"},"outputs":[],"source":["def average(numbers):\n"," \"\"\"\n"," Parameters\n"," ----------\n"," numbers: list\n"," The input list.\n"," Returns\n"," -------\n"," ave : int\n"," The average of the input list, if the input is empty please return None\n"," \"\"\"\n"," # Your code here\n"," # Special case: If the numbers list is empty, return None:\n"," if ():\n"," return None\n","\n"," # Loop over each number in numbers:\n","\n","\n"," # Get the average by dividing the total by how many numbers there are:\n","\n"," return ave"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"QnOTzsRCUdQz"},"outputs":[],"source":["assert average([1, 2, 3]) == 2\n","assert average([12, 20, 37]) == 23\n","assert average([0, 0, 0, 0, 0]) == 0\n","assert average([]) == None"]},{"cell_type":"markdown","metadata":{"id":"7YVyJ-IgBZ7s"},"source":["### List methods"]},{"cell_type":"markdown","metadata":{"id":"4_9Odb1wcyXb"},"source":["The `+` operator concatenates lists:"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"8F9HmW2TBIM5"},"outputs":[],"source":["a = [1, 2, 3]\n","b = [4, 5, 6]\n","c = a + b\n","c"]},{"cell_type":"markdown","metadata":{"id":"gJBaw99Jc78a"},"source":["Similarly, the `*` operator repeats a list a given number of times:"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"b1L77iBcc5BG"},"outputs":[],"source":["[1, 2, 3] * 3"]},{"cell_type":"markdown","metadata":{"id":"kCDRoMiLdFn7"},"source":["`append` adds a new element to the end of a list:"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"yzO9iDDwc-eK"},"outputs":[],"source":["t = ['a', 'b', 'c']\n","t.append('d')\n","t # in-place operation!"]},{"cell_type":"markdown","metadata":{"id":"jtNWEpvjdRvZ"},"source":["extend takes a list as an argument and appends all of the elements:"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"1GpPiDMidK3p"},"outputs":[],"source":["t1 = ['a', 'b', 'c']\n","t2 = ['d', 'e']\n","t1.extend(t2)\n","t1"]},{"cell_type":"markdown","metadata":{"id":"ltTvyhYsdzPR"},"source":["There are several ways to delete elements from a list"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"jlIhCLtodaKM"},"outputs":[],"source":["t = ['a', 'b', 'c']\n","del t[1] # using index\n","print(t)\n","t.remove('a') # using the value\n","print(t) "]},{"cell_type":"markdown","metadata":{"id":"RhDCtHL5eKyQ"},"source":["There are a number of built-in functions that can be used on lists that allow you to quickly look through a list without writing your own loops:"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"A01f6wX1d9UV"},"outputs":[],"source":["nums = [3, 41, 12, 9, 74, 15]\n","print(len(nums))"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"SGUBu86tePD2"},"outputs":[],"source":["print(max(nums))\n","print(min(nums))\n","print(sum(nums))"]},{"cell_type":"markdown","metadata":{"id":"pLBqUakio6cY"},"source":["Check out https://docs.python.org/3/tutorial/datastructures.html#more-on-lists for more methods!"]},{"cell_type":"markdown","metadata":{"id":"L5VlI3VKg_dV"},"source":["### List and strings"]},{"cell_type":"markdown","metadata":{"id":"90_U8UuRhGW0"},"source":["A string is a sequence of characters and a list is a sequence of values, but a list of characters is not the same as a string. To convert from a string to a list of characters, you can use `list`:"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"5myqyQ-teVE1"},"outputs":[],"source":["s = 'nsysu math'\n","t = list(s)\n","print(t)"]},{"cell_type":"markdown","metadata":{"id":"PurBoAMOhf0P"},"source":["The list function breaks a string into individual letters. If you want to break a string into words, you can use the split method:"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"Di8IVn1-hOBR"},"outputs":[],"source":["r = s.split()\n","r"]},{"cell_type":"markdown","metadata":{"id":"KRF_niV4hp0d"},"source":["`join` is the inverse of `split`. It takes a list of strings and concatenates the elements. join is a string method, so you have to invoke it on the delimiter and pass the list as a parameter:"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"VpVofuR3hj6T"},"outputs":[],"source":["delimiter = ' ' # note the white space!\n","delimiter.join(r)"]},{"cell_type":"markdown","metadata":{"id":"wgqoOGqEiUre"},"source":["### Aliasing and list arguments"]},{"cell_type":"markdown","metadata":{"id":"HnWwW6USiYmc"},"source":["If `a `refers to an object and you assign b = a, then both variables refer to the same objec. To check whether two variables refer to the same object, you can use the `is` operator"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"VZo8S-LZh8DU"},"outputs":[],"source":["a = [1, 2, 3]\n","b = a\n","b is a"]},{"cell_type":"markdown","metadata":{"id":"DdSrQ591irEE"},"source":["The association of a variable with an object is called a *reference*. In this example, there are two references to the same object. An object with more than one reference **has more than one name**, so we say that the object is *aliased*."]},{"cell_type":"markdown","metadata":{"id":"8zC9unEai3_-"},"source":["If the aliased object is mutable, changes made with one alias affect the other!"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"7f1XBo8Iig2u"},"outputs":[],"source":["b[0] = 17\n","print(a)"]},{"cell_type":"markdown","metadata":{"id":"WBmdvHwqi9BU"},"source":["**When you pass a list to a function, the function gets a reference to the list. If the function modifies a list parameter, the caller sees the change.** For example, `delete_head` removes the first element from a list:"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"NuG_Kdp2i8ZT"},"outputs":[],"source":["def delete_head(t):\n"," del t[0]"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"C5mfMtTai69t"},"outputs":[],"source":["letters = ['a', 'b', 'c']\n","delete_head(letters)\n","print(letters)"]},{"cell_type":"markdown","metadata":{"id":"Wk6SJP_DjSKt"},"source":["The parameter t and the variable letters are aliases for the same object!\n","\n","Check out [here](https://pythontutor.com/render.html#code=subjects%20%3D%20%5B'calculus',%20'introduction%20to%20mathematics',%20'introduction%20to%20computer%20science',%20'linear%20algebra'%5D%0Amy_course%20%3D%20subjects%0Amy_course.append%28'English'%29%0Anew_course%20%3D%20subjects.copy%28%29%0Anew_course.remove%28'English'%29&cumulative=false&curInstr=0&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=3&rawInputLstJSON=%5B%5D&textReferences=false)"]},{"cell_type":"markdown","metadata":{"id":"UVyscPC3mYeo"},"source":["## Dictionaries"]},{"cell_type":"markdown","metadata":{"id":"MOGo5JaVmdnJ"},"source":["A *dictionary* is like a list, but more general. In a list, the index positions have to be integers; in a dictionary, the indices can be (almost) any type.\n","\n","You can think of a dictionary as a mapping between a set of indices (which are called keys) and a set of values. Each key maps to a value. The association of a key and a value is called a `key-value` pair or sometimes an item."]},{"cell_type":"markdown","metadata":{"id":"42QE-OUnptIL"},"source":["
\n","
source: https://favtutor.com/blogs/list-vs-dictionary
"]},{"cell_type":"markdown","metadata":{"id":"I1zr7rV8d2Oa"},"source":["> As of Python 3.7, dictionary items maintain the order at which they are inserted into the dictionary."]},{"cell_type":"markdown","metadata":{"id":"tB2j7j3YmpRZ"},"source":["As an example, we’ll build a dictionary that maps from subjects to grade, so the keys are string while the values are integers. The function `dict` creates a new dictionary with no items. "]},{"cell_type":"code","execution_count":1,"metadata":{"id":"TXcMt4SuqC7c"},"outputs":[{"data":{"text/plain":["dict"]},"execution_count":1,"metadata":{},"output_type":"execute_result"}],"source":["type({})"]},{"cell_type":"code","execution_count":2,"metadata":{"id":"JKYIUUsujPRj"},"outputs":[{"data":{"text/plain":["{}"]},"execution_count":2,"metadata":{},"output_type":"execute_result"}],"source":["grade = dict()\n","grade"]},{"cell_type":"markdown","metadata":{"id":"M3f_fuvfm7SD"},"source":["To add items to the dictionary, you can use square brackets:"]},{"cell_type":"code","execution_count":3,"metadata":{"id":"Crr5iMsmm7j6"},"outputs":[{"name":"stdout","output_type":"stream","text":["{'calculus': 85}\n"]}],"source":["grade['calculus'] = 85\n","print(grade)"]},{"cell_type":"code","execution_count":4,"metadata":{"id":"PpP_327sn4Xn"},"outputs":[{"data":{"text/plain":["{'calculus': 85,\n"," 'introduction to mathematics': 80,\n"," 'introduction to computer science': 90,\n"," 'linear algebra': 95}"]},"execution_count":4,"metadata":{},"output_type":"execute_result"}],"source":["grade = {'calculus':85, 'introduction to mathematics':80, 'introduction to computer science':90, 'linear algebra':95}\n","grade"]},{"cell_type":"markdown","metadata":{"id":"D2qbNFSAnt5Z"},"source":["You can\tstore them using separate lists for\tsubjects and scores but the following update and maintain will becomes tedius"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"CA6T9WXNnBcY"},"outputs":[],"source":["subjects = ['calculus', 'introduction to mathematics', 'introduction to computer science', 'linear algebra']\n","score = [85, 80, 90, 95]"]},{"cell_type":"markdown","metadata":{"id":"QX4Ti3yEod_A"},"source":["You can now use the keys to look up the corresponding values:"]},{"cell_type":"code","execution_count":5,"metadata":{"id":"mo31IN5toMnq"},"outputs":[{"name":"stdout","output_type":"stream","text":["90\n"]}],"source":["print(grade['introduction to computer science'])"]},{"cell_type":"markdown","metadata":{"id":"XhA3QGXqoqD_"},"source":["The `in` operator works on dictionaries; it tells you whether something appears as a key in the dictionary."]},{"cell_type":"code","execution_count":6,"metadata":{"id":"kmCBCvvpokWE"},"outputs":[{"data":{"text/plain":["(True, False)"]},"execution_count":6,"metadata":{},"output_type":"execute_result"}],"source":["'calculus' in grade, 'English' in grade"]},{"cell_type":"markdown","metadata":{"id":"biss6VA0qehV"},"source":["To add or delete an entry, it is similar to list"]},{"cell_type":"code","execution_count":10,"metadata":{"id":"eI4RAkSFqlPM"},"outputs":[{"data":{"text/plain":["{'calculus': 85,\n"," 'introduction to mathematics': 80,\n"," 'introduction to computer science': 90,\n"," 'linear algebra': 95,\n"," 'English': 100}"]},"execution_count":10,"metadata":{},"output_type":"execute_result"}],"source":["grade['English'] = 100\n","grade"]},{"cell_type":"code","execution_count":11,"metadata":{"id":"qom8rf_zqq9O"},"outputs":[{"data":{"text/plain":["{'calculus': 85,\n"," 'introduction to mathematics': 80,\n"," 'introduction to computer science': 90,\n"," 'linear algebra': 95}"]},"execution_count":11,"metadata":{},"output_type":"execute_result"}],"source":["del(grade['English'])\n","grade"]},{"cell_type":"markdown","metadata":{"id":"GzwHWKMpSnRP"},"source":["Note that you can’t access items in them using integer indexes like `grade[0]`. (Consider the case when you use 4, 2, 1, 0 as the keys)"]},{"cell_type":"markdown","metadata":{"id":"6RCf2QXSpQJv"},"source":["### Looping and dictionaries"]},{"cell_type":"markdown","metadata":{"id":"XAHxIF6opTy4"},"source":["If you use a dictionary as the sequence in a for statement, it traverses the keys of the dictionary. This loop prints each key and the corresponding value:"]},{"cell_type":"code","execution_count":14,"metadata":{"id":"-IszozMCoylO"},"outputs":[{"name":"stdout","output_type":"stream","text":["calculus 85\n","introduction to mathematics 80\n","introduction to computer science 90\n","linear algebra 95\n"]}],"source":["for key in grade:\n"," print(key, grade[key])"]},{"cell_type":"markdown","metadata":{"id":"7lbwQCgXpj4W"},"source":["The `for` loop iterates through the keys of the dictionary, so we must use the index operator to retrieve the corresponding value for each key."]},{"cell_type":"markdown","metadata":{"id":"zF4SH17xpv5n"},"source":["If you want to retrieve all the keys and values, you can use the `keys` and `values` method available in dictionary objects"]},{"cell_type":"code","execution_count":16,"metadata":{"id":"Qfh-dIbtpY8y"},"outputs":[{"name":"stdout","output_type":"stream","text":["['calculus', 'introduction to mathematics', 'introduction to computer science', 'linear algebra']\n","[85, 80, 90, 95]\n"]}],"source":["subject = list(grade.keys())\n","score = list(grade.values())\n","print(subject)\n","print(score)"]},{"cell_type":"markdown","metadata":{"id":"jscaE3K65HP9"},"source":["### > Exercise 3: Try to write a function that calculates the weighted average of the input dictionary"]},{"cell_type":"code","execution_count":17,"metadata":{"id":"K60lVWx3WDoN"},"outputs":[],"source":["def weight_average(grade, weight):\n"," \"\"\"\n"," Parameters\n"," ----------\n"," grade: dict\n"," The key is the subject while the value stores the corresponding score\n"," weight: list\n"," The weight of each corresponding subject in grade\n"," Returns\n"," -------\n"," score : int\n"," The final weighted average score\n"," \"\"\"\n"," # Your code here\n"," for idx, key in enumerate(grade):\n"," return score"]},{"cell_type":"code","execution_count":18,"metadata":{"id":"2gmdRMcXWMbF"},"outputs":[],"source":["assert(weight_average(grade, [1,1,1,1])) == 87.5\n","assert(weight_average(grade, [4,1,2,1])) == 86.875"]},{"cell_type":"markdown","metadata":{"id":"UMo588t4rY-O"},"source":["## Tuples"]},{"cell_type":"markdown","metadata":{"id":"3cbVny0qrb2X"},"source":["A tuple is a sequence of values much like a list. The values stored in a tuple can be any type, and they are indexed by integers. The important difference is that tuples are immutable."]},{"cell_type":"markdown","metadata":{"id":"ZBmWzbZrrodF"},"source":["Although it is not necessary, it is common to enclose tuples in parentheses to help us quickly identify tuples when we look at Python code:"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"31nRYo3kp8pZ"},"outputs":[],"source":["type(())"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"byFxBdL-p0W7"},"outputs":[],"source":["t = ('a', 'b', 'c', 'd', 'e')\n","t"]},{"cell_type":"markdown","metadata":{"id":"ljwYA7Bnrtfi"},"source":["To create a tuple with a single element, you have to include the final comma or use the `tuple` method"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"7bKaCxd6rm3o"},"outputs":[],"source":["t1 = ('a',)\n","print(t1)\n","t2 = tuple('a')\n","print(t2)"]},{"cell_type":"markdown","metadata":{"id":"49oF_8Z_r-jU"},"source":["If the argument is a sequence (string, list, or tuple), the result of the call to tuple is a tuple with the elements of the sequence:"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"HpZ5N3P-r4NB"},"outputs":[],"source":["t = tuple('nsysu')\n","t"]},{"cell_type":"markdown","metadata":{"id":"uCQoFLN6sFSN"},"source":["Most list operators also work on tuples. The bracket operator indexes an element:"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"qZmPRU1OsBxR"},"outputs":[],"source":["print(t[0])\n","print(t[1:3])"]},{"cell_type":"markdown","metadata":{"id":"1_iwRUm4sNKE"},"source":["But if you try to modify one of the elements of the tuple, you get an error:"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"bZZIW_AssHyW"},"outputs":[],"source":["t[0] = 'A'"]},{"cell_type":"markdown","metadata":{"id":"AGs4jgnSsZa1"},"source":["### Dictionaries and tuples"]},{"cell_type":"markdown","metadata":{"id":"_bWKfSrwsber"},"source":["Dictionaries have a method called `items` that returns a list of tuples, where each tuple is a key-value pair:"]},{"cell_type":"code","execution_count":19,"metadata":{"id":"nqNW-NBbsO8A"},"outputs":[{"data":{"text/plain":["[('calculus', 85),\n"," ('introduction to mathematics', 80),\n"," ('introduction to computer science', 90),\n"," ('linear algebra', 95)]"]},"execution_count":19,"metadata":{},"output_type":"execute_result"}],"source":["t = list(grade.items())\n","t"]},{"cell_type":"markdown","metadata":{"id":"uXNIm4G4szJG"},"source":["Combining items, tuple assignment, and `for`, you can see a nice code pattern for traversing the keys and values of a dictionary in a single loop:"]},{"cell_type":"code","execution_count":21,"metadata":{"id":"N8GGcAX-sgo8"},"outputs":[{"name":"stdout","output_type":"stream","text":["calculus 85\n","introduction to mathematics 80\n","introduction to computer science 90\n","linear algebra 95\n"]}],"source":["for key, val in list(grade.items()):\n"," print(key,val)"]},{"cell_type":"markdown","metadata":{"id":"nSxBNltDtEvt"},"source":["In many contexts, the different kinds of sequences (strings, lists, and tuples) can be used interchangeably. So how and why do you choose one over the others?\n","\n","To start with the obvious, strings are more limited than other sequences because the elements have to be characters. They are also immutable. If you need the ability to change the characters in a string (as opposed to creating a new string), you might want to use a list of characters instead.\n","\n","Lists are more common than tuples, mostly because they are mutable. But there are a few cases where you might prefer tuples:\n","\n","1. In some contexts, like a return statement, it is syntactically simpler to create a tuple than a list. In other contexts, you might prefer a list.\n","\n","2. If you want to use a sequence as a dictionary key, you have to use an immutable type like a tuple or string.\n","\n","3. If you are passing a sequence as an argument to a function, using tuples reduces the potential for unexpected behavior due to aliasing.\n","\n","Because tuples are immutable, they don’t provide methods like `sort` and `reverse`, which modify existing lists. However Python provides the built-in functions `sorted` and `reversed`, which take any sequence as a parameter and return a new sequence with the same elements in a different order."]},{"cell_type":"code","execution_count":25,"metadata":{"id":"SimsATIueN_v"},"outputs":[{"data":{"text/plain":["(10, 5)"]},"execution_count":25,"metadata":{},"output_type":"execute_result"}],"source":["a = 10\n","b = 5\n","a,b"]},{"cell_type":"code","execution_count":null,"metadata":{},"outputs":[],"source":[]}],"metadata":{"colab":{"collapsed_sections":["SwFKFBMwRzoa","n3ezAAdIsgpj","gASYx5-Cxzyg","2kLRVhae3rSa","DPpfFEA07W0A","uloOTsPL9A74","MTJO4K049nuU","3hD9uBt6AW9l","IvviPig3At12","HQK5zGP749m3","7YVyJ-IgBZ7s","L5VlI3VKg_dV","wgqoOGqEiUre","jscaE3K65HP9","UMo588t4rY-O","AGs4jgnSsZa1"],"provenance":[],"toc_visible":true},"kernelspec":{"display_name":"Python 3.8.8 ('base')","language":"python","name":"python3"},"language_info":{"codemirror_mode":{"name":"ipython","version":3},"file_extension":".py","mimetype":"text/x-python","name":"python","nbconvert_exporter":"python","pygments_lexer":"ipython3","version":"3.8.8"},"vscode":{"interpreter":{"hash":"ffe9a5d1be64f395cda62646beb00f4fbc1d5c319e2b42024d6d4b4beddf19a5"}}},"nbformat":4,"nbformat_minor":0}